package com.changan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changan.entity.*;
import com.changan.exception.BusinessException;
import com.changan.jwt.JWTToken;
import com.changan.mapper.*;
import com.changan.response.ResultCode;
import com.changan.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.utils.JWTUtils;
import com.changan.utils.MD5Utils;
import com.changan.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2022-08-30
 */
@Service
public class UserServiceImp extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public Page<User> getUserByPage(Page<User> page, UserVO userVO) {
        List<User> users = this.baseMapper.getUserByPage(page,userVO);
        page.setRecords(users);
        return page;
    }

    @Override
    public void exportExcel(HttpServletResponse response, UserVO userVO) throws IOException {
        List<User> users = this.baseMapper.getUserListByVO(userVO);

//        String fileName = "用户信息.xlsx";
//        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//        // 如果这里想使用03 则 传入excelType参数即可
//        EasyExcel.write(fileName, User.class)
//                .sheet("模板")
//                .doWrite(() -> {
//                    // 分页查询数据
//                    return users;
//                });

        //----- 写入excel文件
        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    @Override
    public String login(String username, String password) {
        //判断用户密码是否为空
        if(StringUtils.isEmpty(username)){
            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getCode(),ResultCode.PARAM_IS_BLANK.getMessage());
        }
        //根据用户查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user = this.baseMapper.selectOne(wrapper);
        if(user == null){
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }

        //3验证密码
        //获取数据库加密的密码
        String encryptPassword = user.getPassword();
        //获取数据库的盐
        String salt = user.getSalt();
        //对原始密码进行加密加盐
        String md5Encryption = MD5Utils.md5Encryption(password, salt);
        if(!md5Encryption.equals(encryptPassword)){
            throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        }
        //4.生成token
        String token = JWTUtils.sign(username, md5Encryption);
        JWTToken jwtToken = new JWTToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
        } catch (AuthenticationException e) {
            throw new ServiceException(e.getMessage());
        }
        return token;
    }

    @Override
    public List<Role> findRolesById(Long id) {
        User dbUser = this.baseMapper.selectById(id);
        if(dbUser==null){
            throw new ServiceException("该用户不存在");
        }
        List<Role> roles=new ArrayList<>();
//        UserRole t = new UserRole();
//        t.setUserId(dbUser.getId());
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId,dbUser.getId());
        List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);
        List<Long> rids=new ArrayList<>();
        if(!CollectionUtils.isEmpty(userRoleList)){
            for (UserRole userRole : userRoleList) {
                rids.add(userRole.getRoleId());
            }
            if(!CollectionUtils.isEmpty(rids)){
                for (Long rid : rids) {
                    Role role = roleMapper.selectById(rid);
                    if(role!=null){
                        roles.add(role);
                    }
                }
            }
        }
        return roles;
    }

    @Override
    public List<Menu> findMenuByRoles(List<Role> roles) {
        List<Menu> menus=new ArrayList<>();
        if(!CollectionUtils.isEmpty(roles)){
            Set<Long> menuIds=new HashSet<>();//存放用户的菜单id
            List<RoleMenu> roleMenus;
            for (Role role : roles) {
                //根据角色ID查询权限ID
//                Example o = new Example(RoleMenu.class);
//                o.createCriteria().andEqualTo("roleId",role.getId());
                LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(RoleMenu::getRoleId,role.getId());
                roleMenus= roleMenuMapper.selectList(wrapper);
                if(!CollectionUtils.isEmpty(roleMenus)){
                    for (RoleMenu roleMenu : roleMenus) {
                        menuIds.add(roleMenu.getMenuId());
                    }
                }
            }
            if(!CollectionUtils.isEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    //该用户所有的菜单
                    Menu menu = menuMapper.selectById(menuId);
                    if(menu!=null){
                        menus.add(menu);
                    }
                }
            }
        }
        return menus;
    }
}
